package com.heima.list;

import java.util.ArrayList;

/*
    String集合
    存储{test,张三,李老四,王二,test,test}
    删除所有test
    打印剩余元素
 */
public class ListDelete {
    public static void main(String[] args) {
//      定义并初始化集合(一级引用)
        ArrayList<String> strList = new ArrayList<>();
//      存储{test,张三,李老四,王二,test,test}
        //声明并初始化字符串数组(二级引用)
        String[] s = {"test","张三","李老四","王二","test","test"};
        //将字符串数组存入集合
        getString(strList, s);
        System.out.println(strList);
//      删除所有test
        delete(strList,"test");
//      打印剩余元素
        System.out.println(strList);
    }
    /*
        优化: 直接从末尾开始查找并删除,就不需要回退机制
        public static void delete(ArrayList<String> strList,String s) {
        for (int i = strList.size()-1; i >= 0; i--) {
            if(strList.get(i).equals(s)){//判断该位是否是要删除字符串
                strList.remove(i);//不需回退
            }
        }
    }
     */
    public static void delete(ArrayList<String> strList,String s) {
        for (int i = 0; i < strList.size(); i++) {
            if(strList.get(i).equals(s)){//判断该位是否是要删除字符串
                strList.remove(i);
                i--;//回退
            }
        }
    }

    public static void getString(ArrayList<String> strList, String[] s) {
        for (int i = 0; i < s.length; i++) {
            strList.add(i, s[i]);
        }
    }
}
